class Post < ActiveRecord::Base
  belongs_to :topic, :counter_cache => true
  belongs_to :user
  
  validates_presence_of :content
  format_attribute :content
  
  after_save :update_topic_after_save
  
  def editable_by?(user)
    user!=:false && (user.id==user_id || user.is_admin? || user.moderator_of?(self.topic.group))
  end
  
  private
  def update_topic_after_save
    topic = self.topic
    topic.posts_count = Post.count(:id, :conditions => {:topic_id => topic.id})
    topic.replied_at = self.updated_at
    topic.replied_by_user = self.user
    topic.save!
  end
end
